import {apiMethod} from "@/apis/apis";
import router from "@/router";
import store from '@/store/index';
import {RouteNameEnum} from "@/common-class/common-config/RouteClass";
import {ElFormComponent} from "@/plugins/element";
import {Loading} from "@/common-class/model/Wind3Loading";
import {Wind3User} from "@/common-class/model/Wind3User";
import {ApiCode} from "@/common-class/common-config/ApiClass";

/**
 * 用户注销登录功能
 */
export async function logout(): Promise<void> {
  await apiMethod.logout();
  await store.dispatch('user/asyncSetToken', null);
  await store.dispatch('user/asyncSetUser', null);
  await router.push({ name: RouteNameEnum.login });
}

/**
 * 用户登录功能
 * @param loginFormUser 登录用户类
 * @param loginForm 校验form表单本身
 * @param loading load对象
 */
export async function submitLogin(
  loginFormUser: Wind3User,
  loginForm: ElFormComponent,
  loading: Loading): Promise<void> {
  const data: boolean = await loginForm.validate();
  loading.status = true;
  if (data) {
    const res = await apiMethod.login(loginFormUser);
    loading.status = false;
    if (res.apiCode === ApiCode.Success && res.result) {
      await store.dispatch('user/asyncSetToken', res.result.token);
      await store.dispatch('user/asyncSetUser', res.result.wind3User);
      await router.push({name: RouteNameEnum.home});
    }
  }
}
